<template>
  <div class="add-user">
    <el-form
      :inline="true"
      :rules="rules"
      ref="ruleForm"
      :model="dataForm"
      label-width="120px"
      class="dialog"
      :label-position="labelPosition"
      autocomplete="off"
    >
      <el-row :gutter="20">
        <el-col :span="12" style="position:relative">
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="dataForm.name"
              placeholder="请输入角色名称"
              clearable
            ></el-input>
          </el-form-item>
          <p
            style="color:#F56C6C;margin-left:130px;margin-bottom:20px;font-size:12px;position:absolute;left:0;top:45px;"
            v-if="validteGroupNo"
          >该角色名称已存在,请重新输入</p>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="dataForm.description" placeholder="请输入角色描述"  clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权限设置">
            <el-tree
              ref="menuListTree"
              :data="data2"
              show-checkbox
              node-key="id"
              :default-expand-all="true"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>
        </el-col>
      </el-row>
<!-- 
      <el-row :gutter="20">
           <el-col :span="12">
          <el-form-item label="角色类型">
            <el-select v-model="value" placeholder="请选择" @change="selectUserType">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公司名称" prop="companyCodes">
           <el-select v-model="dataForm.company_code" placeholder="请选择" :disabled="componydisabled">
              <el-option
                v-for="item in companList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
    
      </el-row> -->
      <el-row :gutter="20">
        <el-col :span="23">
          <el-form-item prop="remark" label="备注">
          <el-input type="textarea" :rows="5" placeholder="请输入备注" clearable v-model="dataForm.remark"></el-input>
         </el-form-item>
        </el-col>
      </el-row>
      <el-form-item style="margin-top:20px;margin-bottom:100px;text-align:center;">
        
        <el-button type="primary"  @click="doneFinshed('ruleForm')" :disabled="isDabled">确认</el-button>
        <el-button type="info" @click="backPrev">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {

  data () {
    var names = (rule, value, callback) => {
      var data = {
        name: this.dataForm.name
      }
      if (value == '') {
        callback(new Error('角色名称不允许为空'))
      } else if (value && !this.noRepeat) {
        this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/role/checkOnly`, data).then((res) => {
          if (res.result) {
            this.noRepeat = res.data
            if (this.noRepeat == false) { // res.data.data [true]有重复/【false】无重复
              callback(new Error('该角色名称已存在,请重新输入'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    return {
      userRole: [],
      options: [],
      value: '',
      disabled: false,
      validteGroupNo: false,
      dataForm: {
        rolesCodes: [],
        company_code: '',
        name: '',
        description: '',
        remark: ''

      },
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      data2: [],
      nodes: [],
      sysCode: ['sys_role'],
      companList: [],
      roledisabled: true,
      componydisabled: true,
      labelPosition: 'right',
      rules: {
        name: [
          { validator: names, required: true, trigger: 'blur' },
          { min: 1, max: 64, message: '长度不可超过64个字符', trigger: 'blur' }
        ],
        description: [
          { min: 1, max: 128, message: '长度不可超过128个字符', trigger: 'blur' }
        ],
        remark: [
           { min: 2, max: 255, message: '长度不可超过255个字符', trigger: 'blur' }
        ]
      },
      isDabled: false
    }
  },
  mounted () {
    this.getDictionaryByType()
    this.getCompanList()
    this.lookPermission()
  },

  methods: {
    backPrev () {
      this.$router.go(-1)
    },
    lookPermission () {
      var code = this.$route.query.code
      this.dialogVisible = true
      this.code = code
      this.nodes = []
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/role/findPermissionOfRole`, {roleCode: code}).then((res) => {
        this.data2 = this.treeDataTranslate(res.data, 'code')
        console.log('data2', this.data2)
        this.getNodes(this.data2)
        console.log('nodes', this.nodes)
        this.$refs.menuListTree.setCheckedKeys(this.nodes)
      })
    },
    treeDataTranslate (data, id = 'code', pid = 'parentCode') {
      var res = []
      var temp = {}
      for (var i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i]
      }
      for (var k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
          if (!temp[data[k][pid]]['children']) {
            temp[data[k][pid]]['children'] = []
          }
          if (!temp[data[k][pid]]['level']) {
            temp[data[k][pid]]['level'] = 1
          }
          data[k]['level'] = temp[data[k][pid]].level + 1
          temp[data[k][pid]]['children'].push(data[k])
        } else {
          res.push(data[k])
        }
      }
      return res
    },
    // 检测用户名唯一性
    checkOnly (index) {
      if (this.dataForm.username == '') {
        return
      }
      var data = {}
      if (index == 1) {
        data = {
          name: this.dataForm.name
        }
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/role/checkOnly`, data)
        .then(res => {
          if (res.result) {
            if (res.data) {
              if (index == 1) {
                this.validteGroupNo = false
              } else {
                this.validateName = false
              }
            } else {
              if (index == 1) {
                this.validteGroupNo = true
              } else {
                this.validateName = true
              }
            }
          }
        })
    },
    // 递归获取节点
    getNodes (treenodes) {
      if (treenodes.length > 0) {
        for (var i = 0; i < treenodes.length; i++) {
          if (treenodes[i].children) {
            this.getNodes(treenodes[i].children)
          } else {
            if (treenodes[i].selected) {
              this.nodes.push(treenodes[i].id)
            }
          }
        }
      }
    },
    getDictionaryByType () {
      var data = {
        type: 'roleType'
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/dictionary/findDictionaryByType`, data).then((res) => {
        var result = res.data
        var delData = []
        if (res.result) {
          for (var k in result) {
            delData.push({value: result[k].dicCode, label: result[k].dicValue})
          }
          this.options = delData
        }
      })
    },
    selectUserType () {
      if (this.value === 'sys_role') {
        this.componydisabled = true
        this.dataForm.company_code = ''
      } else {
        this.componydisabled = false
        this.getCompanList()
      }
    },
    getCompanList () {
      var data = {
        companyNo: '',
        name: ''
      }
      this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/company/findCompanyList`, data).then((res) => {
        var result = res.data
        var delData = []
        if (res.result) {
          for (var k in result) {
            delData.push({value: result[k].code, label: result[k].name})
          }
          this.companList = delData
        }
      })
    },
    doneFinshed (formName) {
      let keyList = this.$refs.menuListTree.getCheckedNodes()
      let halfKeyList = this.$refs.menuListTree.getHalfCheckedNodes()
      let result = keyList.concat(halfKeyList).map(item => item.code)
      var data = {
        roleType: this.value,
        operateType: 'save',
        role: {
          name: this.dataForm.name,
          description: this.dataForm.description,
          remark: this.dataForm.remark,
          company_code: this.dataForm.company_code

        },
        permissionCodes: result

      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          // if (this.value !== 'sys_role') {
          //   if (this.dataForm.company_code === '') {
          //     this.$message({
          //       message: '请选择公司',
          //       type: 'warning'
          //     })
          //     return
          //   }
          // }
          this.isDabled = true
          this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/role/operationData`, data).then((res) => {
            if (res.result) {
              this.$message({
                message: '操作成功',
                type: 'success'
              })

              this.$router.push('/systemSettings/role/list')
            } else {
              this.isDabled = false
              this.$message.error({
                message: res.msg,
                duration: 5000
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style>
.dialog .el-form-item__content {
  width: 70%;
}
.dialog .el-form-item {
  width: 100%;
}
.dialog .el-select {
  width: 100%;
}
.el-form-item__label {
  text-align: right;
}

</style>

<style lang="scss" scoped>
.add-user {
  background: #fff;
  padding-top: 20px;
  padding-left: 20px;
}
</style>

